package com.lg.desireplayer.main;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.lg.desireplayer.R;
import com.lg.desireplayer.bandinfo.AddBandinfo;
import com.lg.desireplayer.bandinfo.ViewBandinfo;
import com.lg.desireplayer.bandlist.BandList;
import com.lg.desireplayer.db.BandListMaker;
import com.lg.desireplayer.db.LikeUpdater;
import com.lg.desireplayer.member.Login;
import com.lg.desireplayer.ranking.RankTabMain;
import com.lg.desireplayer.search.SearchTap;
import com.lg.desireplayer.util.GetImageFromURL;

public class Main extends Activity implements OnClickListener {
	private Button Btn_Rank;
	private Button Btn_Search;
	private Button Btn_Login;
	private Button Btn_Setting; 
	
	private ImageButton Btn_list1_Down;
	private ImageButton Btn_list1_Play;
	private ImageButton Btn_list1_Like;
	private ImageButton Btn_list1_Info;
	private ImageView Image_list1_Background;
	private ProgressBar progressBar1;
	
	private ViewFlipper m_viewFlipper2;
	private ImageView Image_list2_Background;
	
	private int m_nPreTouchPosX = 0;
	private int m_nPreTouchPosY = 0;
	
	private Intent intent;
	private StreamingMediaPlayer audioStreamer1;
	
	private boolean isPlaying1;
	private boolean isFirst=true;
	
	private ArrayList<Integer> b_callLog = new ArrayList<Integer>();
	private ArrayList<Integer> callLog = new ArrayList<Integer>();
	
	private int DB_SIZE;
	private int INIT_ID;
	private int RANDOM_ID;
	private int CURRENT_ID;
	private TextView Text_list1_Title;
	
	private int userMode;
	private int userID;
	private ProgressDialog dialog;
	
	int searchMode;
	int infoMode;
	
	int count = 0 ;
	
	private ArrayList<Bitmap> images = new ArrayList<Bitmap>();
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			dialog.dismiss();
			if( userMode == 0 )  {
				Btn_Login.setVisibility(View.GONE);
				Btn_Setting.setVisibility(View.GONE);
			}
			else if ( userMode == 1 ){
				Btn_Login.setVisibility(View.GONE);
			}
			else if ( userMode == 2 ){
				Btn_Setting.setVisibility(View.GONE);
			}
			
			
			//화면전환에 따른 설정 변경
			//로그인->메인
			if(searchMode == -1 && infoMode == -1){
				Log.i("desire","main:1");
				Image_list1_Background.setImageBitmap(images.get(INIT_ID));
				Image_list2_Background.setImageBitmap(images.get(getCurrentCursor()));
				Text_list1_Title.setText(BandList.retrieveBand(INIT_ID).getTitle());
			}
			//서치 -> 메인
			else if(searchMode != -1){
				Log.i("desire","main:2");
				INIT_ID = searchMode;
				Image_list1_Background.setImageBitmap(images.get(INIT_ID));
				Text_list1_Title.setText(BandList.retrieveBand(INIT_ID).getTitle());
				Image_list2_Background.setImageBitmap(images.get(getNextCursor()));
				isPause(1);
				
			}
			//정보 -> 메인
			else if(infoMode != -1){
				Log.i("desire","main:3");
				INIT_ID = infoMode;
				Image_list1_Background.setImageBitmap(images.get(INIT_ID));
				Text_list1_Title.setText(BandList.retrieveBand(INIT_ID).getTitle());
				Image_list2_Background.setImageBitmap(images.get(getNextCursor()));
				isPause(1);
			}
			
		}
	};
	
	@Override
	protected void
	onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		count = 0 ;
		//밴드 정보를 불러오는 로직
		dialog = ProgressDialog.show(Main.this, "","밴드 정보를 불러오는 중입니다. 잠시만 기다려주세요", true);
		
		DB_SIZE = BandList.getSize();
		Log.i("desire","size : "+DB_SIZE);
		//DB에 있는 모든 ID 정보를 가져옴
		ArrayList<Integer> random = new ArrayList<Integer>();
		random.add((int)(Math.random() * DB_SIZE));
		for(int i=1; i<DB_SIZE; i++){
			int temp = (int)(Math.random() * DB_SIZE);
			while(random.contains(temp)){
				temp = (int)(Math.random() * DB_SIZE);
			}
			random.add(temp);
		}
		for (int i = 0; i < random.size(); i++) {
			b_callLog.add(random.get(i));
		}
		INIT_ID= 0;
		RANDOM_ID = 1;
		CURRENT_ID = 1;
		Btn_Rank = (Button)findViewById(R.id.Main_Button_Ranking);
		Btn_Search = (Button)findViewById(R.id.Main_Button_Search);
		Btn_Login = (Button)findViewById(R.id.Main_Button_Login);
		Btn_Setting = (Button)findViewById(R.id.Main_Button_Setting);
		
		View List1 = (View)findViewById(R.id.Main_List_1);
		Btn_list1_Down = (ImageButton)List1.findViewById(R.id.Main_Custom_Button_Down);
		Btn_list1_Play = (ImageButton)List1.findViewById(R.id.Main_Custom_Button_Play);
		Btn_list1_Like = (ImageButton)List1.findViewById(R.id.Main_Custom_Button_Like);
		Btn_list1_Info = (ImageButton)List1.findViewById(R.id.Main_Custom_Button_Info);
		Image_list1_Background = (ImageView)List1.findViewById(R.id.Main_Custom_Image_Back);
		progressBar1 = (ProgressBar) List1.findViewById(R.id.progress_bar);
		Text_list1_Title = (TextView)List1.findViewById(R.id.Main_Custom_Text_Title);
		
		View List2 = (View)findViewById(R.id.Main_List_2);
		m_viewFlipper2 = (ViewFlipper)List2.findViewById(R.id.viewFlipper);
		Image_list2_Background = (ImageView)List2.findViewById(R.id.Main_Custom_Image_Back);
		
		Btn_Rank.setOnClickListener(this);
		Btn_Search.setOnClickListener(this);
		Btn_Login.setOnClickListener(this);
		Btn_Setting.setOnClickListener(this);
		
		m_viewFlipper2.setOnTouchListener(MyTouchListener2);
		
		Btn_list1_Down.setOnClickListener(MyList1ClickListener);
		Btn_list1_Play.setOnClickListener(MyList1ClickListener);
		Btn_list1_Like.setOnClickListener(MyList1ClickListener);
		Btn_list1_Info.setOnClickListener(MyList1ClickListener);

		// 랜덤모드 양수 : search(id) , 음수 : Login();
		// 서치 화면에서 넘어온 케이스
		Intent intent = getIntent();
		searchMode = intent.getIntExtra("Search", -1);
		Log.i("desire", "random : " + searchMode);
		// 밴드 인포에서 넘어온 케이스
		infoMode = intent.getIntExtra("Bandinfo", -1);
		Log.i("desire", "random : " + infoMode);
		// 유저모드 0 : 일반회원, 1 : 밴드회원, 2 : 비회원
		SharedPreferences prefs = getSharedPreferences("Desire", MODE_PRIVATE);
		userMode = prefs.getInt("LoginMode", -1);
		userID = prefs.getInt("LoginID", -1);
		Log.i("desire", "login : " + userMode);
		
		BackThread backThread = new BackThread(handler);
		backThread.start();
		
		
	}
	private int getCurrentCursor(){
		return CURRENT_ID;
	}
	private int getNextCursor(){
		CURRENT_ID = b_callLog.get((RANDOM_ID++)%DB_SIZE);
		return CURRENT_ID;
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		//랭킹
		case R.id.Main_Button_Ranking:
			intent = new Intent(Main.this, RankTabMain.class);
			startActivity(intent);
			overridePendingTransition(R.anim.leftin, R.anim.leftout);
			break;
		//곡&아티스트 검색
		case R.id.Main_Button_Search:
			intent = new Intent(Main.this, SearchTap.class);
			startActivity(intent);
			overridePendingTransition(R.anim.leftin, R.anim.leftout);
			break;
		//로그인
		case R.id.Main_Button_Login:
			intent = new Intent(Main.this, Login.class);
			startActivity(intent);
			finish();
			break;
		//인디밴드 모드
		case R.id.Main_Button_Setting:
			intent = new Intent(Main.this, AddBandinfo.class);
			startActivity(intent);
			overridePendingTransition(R.anim.leftin, R.anim.leftout);
			break;
			
		default:
			break;
		}
	}
	
	private void MoveNextView(int id)
    {
		
		m_viewFlipper2.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.appear_from_right));
		m_viewFlipper2.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.disappear_to_left));
		m_viewFlipper2.showNext();
		callLog.add(getCurrentCursor());
		Image_list2_Background.setImageBitmap(images.get(getNextCursor()));
    }
    
    private void MovewPreviousView(int id)
    {
    	m_viewFlipper2.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.appear_from_left));
		m_viewFlipper2.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.disappear_to_right));
		
	    m_viewFlipper2.showPrevious();
	    Image_list2_Background.setImageBitmap(images.get(getNextCursor()));
    }
    View.OnClickListener MyList1ClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch(v.getId()){
			case R.id.Main_Custom_Button_Down:
				break;
			case R.id.Main_Custom_Button_Play:
				if(  isFirst == true ) {
					startStreamingAudio(BandList.retrieveBand(INIT_ID).getMedia(), 1);
					Btn_list1_Play.setBackgroundResource(R.drawable.main_pause);
					Btn_list1_Play.setEnabled(false);
					isFirst = false;
				}
				else {
					if(isPlaying1){
						isPlay(1);
					}
					else isPause(1);
				}
				break;
			case R.id.Main_Custom_Button_Info:
				Intent intent = new Intent(Main.this, ViewBandinfo.class);
				intent.putExtra("id", INIT_ID);
				intent.putExtra("main", 1);
				startActivity(intent);
				break;
			case R.id.Main_Custom_Button_Like:
				if(userMode == 2){
					Toast.makeText(Main.this, "로그인하세요", Toast.LENGTH_SHORT).show();
				}else {
					Toast.makeText(Main.this, "좋아요", Toast.LENGTH_SHORT).show();
					LikeUpdater.updateLikeCount(INIT_ID, true);
					LikeUpdater.updateLikeMap(userID, INIT_ID);
				}
				break;
			default:
				break;
			}
		}
	};
	//플레이 중이라면
	private void isPlay(int id) {
		if (audioStreamer1 != null) {
			audioStreamer1.getMediaPlayer().start();
			audioStreamer1.startPlayProgressUpdater();
			Btn_list1_Play.setBackgroundResource(R.drawable.main_pause);
			isPlaying1 = !isPlaying1;
		}else isFirst =  true;
	}
	private void isPause(int id){
		if (audioStreamer1 != null) {
			if (audioStreamer1.getMediaPlayer().isPlaying()) {
				audioStreamer1.getMediaPlayer().pause();
				Btn_list1_Play.setBackgroundResource(R.drawable.main_play);
			} 
			isPlaying1 = !isPlaying1;
		}else isFirst =  true;
	}
	//새로 시작할때~
	private void startStreamingAudio(String url, int id) {
    	try { 
			if (audioStreamer1 != null) {
				audioStreamer1.interrupt();
			}
			audioStreamer1 = new StreamingMediaPlayer(this, Btn_list1_Play,	Btn_list1_Down, progressBar1);
			audioStreamer1.startStreaming(url, 5208, 216);
			
    	} catch (IOException e) {
	    	Log.e(getClass().getName(), "Error starting to stream audio.", e);            		
    	}    	    	
    }
    
    View.OnTouchListener MyTouchListener2 = new View.OnTouchListener()
    {
    	public boolean onTouch(View v, MotionEvent event) 
    	{
    		if (event.getAction() == MotionEvent.ACTION_DOWN)
    		{
    			m_nPreTouchPosX = (int)event.getX();
    			m_nPreTouchPosY = (int)event.getY();
    		}
    		
    		if (event.getAction() == MotionEvent.ACTION_UP)
    		{
    			int nTouchPosX = (int)event.getX();
    			int nTouchPosY = (int)event.getY();
    			int dis  = Math.abs(nTouchPosX - m_nPreTouchPosX) - Math.abs(m_nPreTouchPosY - nTouchPosY);
    			
    			if (nTouchPosX - m_nPreTouchPosX > 30 && dis >0)
    			{
    				MovewPreviousView(2);
    			}
    			else if (nTouchPosX - m_nPreTouchPosX < -30 && dis >0)
    			{
    				MoveNextView(2);
    			}
    			
//    			if((nTouchPosX -  m_nPreTouchPosX < 30) && (nTouchPosX -  m_nPreTouchPosX > -30) && dis >0){
//    				upBandInfo();
//    				isPause(0);
//    				isFirst = true;
//    			}
    			if(m_nPreTouchPosY - nTouchPosY > 0 && dis < 0 ){
    				upBandInfo();
    				isPause(0);
    				isFirst = true;
    			}
    			m_nPreTouchPosX = nTouchPosX;
    		}
            return true;
        }
    };
    
    
	@Override
	protected void onDestroy() {
		isPause(1);
		super.onDestroy();
	}
	private void upBandInfo() {
    	Btn_list1_Play.setBackgroundResource(R.drawable.main_play);
    	INIT_ID = getCurrentCursor();
    	Image_list1_Background.setImageBitmap(images.get(getCurrentCursor()));
    	Text_list1_Title.setText(BandList.retrieveBand(getCurrentCursor()).getTitle());
    }
    
    class BackThread extends Thread{
		Handler mhandler;
		BackThread(Handler handler)
		{
			mhandler=handler;
		}
		public void run(){
			
			for(int i=0; i<BandList.getSize();i++){
				images.add(GetImageFromURL.setImage(BandList.retrieveBand(i).getId()));
			}
			mhandler.sendEmptyMessage(0);
		}
	}
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if(keyCode == event.KEYCODE_BACK){
    		if(count==1){
    			finish();
    		}
    		else{
    			count++;
    			Toast.makeText(getApplicationContext(), "한번더 누르시면 종료됩니다.", Toast.LENGTH_SHORT).show();
    		}
    		return false;
    	}
    	return super.onKeyDown(keyCode, event);
    }

}
